package cn.com.nes.site.module.dao.inventory;

import cn.com.nes.common.util.DBUtils;
import cn.com.nes.common.util.Page;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.module.dao.BaseDaoImpl;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Repository
public class OrderOutDaoImpl  extends BaseDaoImpl{
	private TransactionStatus newg_status = null;
	
	@Resource
	private InventoryDaoImpl inventoryDaoImpl;
	
	@Resource
	private OrderInDaoImpl orderInDaoImpl;
	
	public PageData getApplyList(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("获取出库单登记列表失败");
        try {
            StringBuffer sb = new StringBuffer();
            StringBuffer sbfrom = new StringBuffer() ;
            sb.append("select a.uuid,a.applyId,a.purchaseId,a.orderType,b.`name` orderTypeName,a.orderState,c.`name` orderStateName,a.departmentId,e.departmentName,a.applyUid,d.nickName,a.applyTime \n"
            		+ " from g_order_out_apply a \n"
            		+ " left join t_param b on a.orderType=b.`value` and b.param_type='98' \n"
            		+ " left join t_param c on a.orderState=c.`value` and c.param_type='99' \n"
            		+ " left join t_user d on a.applyUid=d.id \n"
            		+ " left join t_department e on a.departmentId=e.departmentId \n"
            		+ " where a.isdelete=0 and serial=1 and  a.companyId='").append(req.getUinfo().getCompanyId()).append("' ");
            
            //状态类型
            if(!StringUtils.isEmpty((String) param.get("stateType"))) {
            	if("01".equals(param.get("stateType"))) {
            		if(!"04".equals(req.getUinfo().getUserType())) {
            			sb.append(" and a.applyUid=").append(req.getUinfo().getId());
            		}
            	}else if("02".equals(param.get("stateType"))) {
            		sb.append(" and a.orderState in ('02','03','04','05') ");
            	}
            }
            //申请类型
            if(!StringUtils.isEmpty((String) param.get("orderType"))) {
            	sb.append(" and a.orderType='").append(param.get("orderType")).append("' ");
            }
            //申请部门
            if(!StringUtils.isEmpty((String) param.get("departmentId"))) {
            	sb.append(" and e.departmentId='").append(param.get("departmentId")).append("' ");
            }
            //申请人
            if(!StringUtils.isEmpty((String) param.get("nickName"))) {
            	sb.append(" and d.nickName like '%").append(param.get("nickName")).append("%' ");
            }
            //登记状态
            if(!StringUtils.isEmpty((String) param.get("orderState"))) {
            	sb.append(" and a.orderState='").append(param.get("orderState")).append("' ");
            }
            //登记开始时间
            if(!StringUtils.isEmpty((String) param.get("startTime"))) {
            	sb.append(" and a.applyTime >= '").append(param.get("startTime")).append("' ");
            }
            //登记结束时间
            if(!StringUtils.isEmpty((String) param.get("endTime"))) {
            	sb.append(" and a.applyTime < '").append(param.get("endTime")).append("' ");
            }
            
            sb.append("  order by a.applyTime desc ");
            sb = DBUtils.sql_check(sb) ;
            sbfrom.append(sb.toString()) ;
            int idx=sbfrom.indexOf(" from ") ;
            sbfrom.delete(0, idx);
            Page page = new Page(this.getJdbcTemplate_newg(),sbfrom.toString(),req.getPageid(),req.getPagesize(),res,new Object[]{}) ;
            sb.append(" limit ").append(page.getOffsetlimit()).append(",").append(req.getPagesize()) ;
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{});
            res.setPage(list);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }
	
	public PageData generateApplyId(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("生成出库申请单号失败");
        try {
        	String orderId = DBUtils.getDjbh(req.getUinfo().getCompanyId(), "SQD") ;
        	res.setKey(orderId);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }
	
	//获取最新申请单ID的序号
	public Integer getApplyNewSerial(String applyId) {
		StringBuffer sb = new StringBuffer();
		sb.append("select serial from g_order_out_apply where applyId='"+applyId+"' order by serial desc limit 1 ");
		List<Map<String, Object>> serial = this.getJdbcTemplate_newg().queryForList(sb.toString());
		if(serial.size()>0) {
			return (Integer) serial.get(0).get("serial");
		}else {
			return null;
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public PageData saveApplyInfo(DataReq req) {
		Map<String, Object> param = req.getReqData();
		PageData res = new PageData();
		newg_status = begin_newg();// 开启事物
		param.put("tableName", "g_order_out_apply");
        param.put("isdelete","0");
        param.put("companyId", req.getUinfo().getCompanyId());
        param.put("applyUid", param.get("applyUid"));
		JSONArray goodslist = (JSONArray) param.get("goodslist");
		try {
	        param.put("orderState", "01");
	        //goodslist不为空 新增
	        if(goodslist.size()>0) {
	        	for(int i=0;i<goodslist.size();i++) {
		        	param.remove("uuid");
		        	JSONObject object = (JSONObject)goodslist.get(i);
		        	param.put("goodsUUid", object.get("goodsUUid"));
		        	param.put("inoutNum", object.get("inoutNum"));
		        	param.put("memo", object.get("memo"));
		        	//设置序号
			        Integer serial = getApplyNewSerial((String) param.get("applyId"));
			        if(serial!=null) {
			        	param.put("serial", String.valueOf(serial+1));
			        }else {
			        	param.put("serial", "1");
			        }
					PageData sqlInfo = getInsertSQL(req);
					if (sqlInfo.getRetCode() != 0) {
						rollback_newg(newg_status);
						return sqlInfo;
					}
					final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
					final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
					this.getJdbcTemplate_newg().update(sb_field.toString(),
							listData.toArray());
		        }
	        }else { //goodslist为空 修改
	        	param.remove("isdelete");
	        	param.put("keys", "applyId") ;
				PageData sqlInfo = getUpdateSQL(req);
				if (sqlInfo.getRetCode() != 0) {
					rollback_newg(newg_status);
					return sqlInfo;
				}
				final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
				final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
				this.getJdbcTemplate_newg().update(sb_field.toString(),
						listData.toArray());
	        }
	        
			
			
			commit_newg(newg_status);
			res.setRetCode(0);
			res.setRetMessage("OK");
		} catch (Exception e) {
			rollback_newg(newg_status);
			e.printStackTrace();
			
		} finally {
			
		}
		return res;
	}
	
	public PageData getApplyDetail(DataReq req) {
        Map<String, Object> param = req.getReqData();
        Map<String,Object> extData = new HashMap();
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("获取出库申请单详情失败");
        try {
            StringBuffer sb = new StringBuffer();
            sb.append("select a.applyId,a.purchaseId,a.orderType,b.`name` orderTypeName,a.orderState,c.`name` orderStateName,"
            		+ " a.departmentId,d.departmentName,a.applyUid,e.nickName applyName,a.applyTime,a.customerID, "
            		+ " a.customerName,a.address,a.phone,a.cusname,a.reviewerId,f.nickName reviewerName,a.reviewerTime,"
            		+ "a.reviewerResult,g.`name` reviewerResultName,a.reviewerSuggest,h.orderId\r\n"
            		+ " from g_order_out_apply a\r\n"
            		+ " left join t_param b on a.orderType=b.`value` and b.param_type='97'\r\n"
            		+ " left join t_param c on a.orderState=c.`value` and c.param_type='99'\r\n"
            		+ " left join t_department d on a.departmentId=d.departmentId\r\n"
            		+ " left join t_user e on a.applyUid=e.id\r\n"
            		+ " left join t_user f on a.reviewerId=f.id\r\n"
            		+ " left join t_param g on a.reviewerResult=g.`value` and g.param_type='100'\r\n"
            		+ "  left join g_order_out h on a.applyId=h.applyId "
            		+ " where a.isdelete=0 and a.serial=1 and a.applyId=? ");
            
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{param.get("applyId")});
            
            List<Map<String,Object>> goodList = new ArrayList<Map<String,Object>>();
            //获取商品列表
            if(list!=null && list.size()>0) {
                	sb.delete(0, sb.length());
                	sb.append("select a.uuid,a.applyId,b.goodsType,d.goodsTypeName,a.goodsUUid,b.goodsCode,"
                			+ " b.goodsName,sum(a.inoutNum) inoutNum ,a.memo,b.brand,b.goodsModel,b.packingSize,b.unit,sum(e.inoutNum) hasoutNum"
                			+ " from g_order_out_apply a\r\n"
                			+ " left join g_goods b on a.goodsUUid=b.uuid\r\n"
                			+ " left join g_goodstype d on b.goodsType=d.goodsTypeId and d.companyId = b.companyId\r\n"
                			+ " left join g_order_out e on a.goodsUUid=e.goodsUUid and a.applyId=e.applyId and isReturn!='1' \r\n"
                			+ " where a.isdelete=0 and a.applyId=?\r\n"
                			+ " group by a.goodsUUid, b.goodsType,d.goodsTypeName,b.goodsCode, b.goodsName,a.memo,b.brand,b.goodsModel,b.packingSize,b.unit \r\n"
                			+ " order by a.serial asc ");
                	List<Map<String, Object>> dto = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{param.get("applyId")});
                	goodList = dto;
            }
            
            extData.put("info", list.size()>0?list.get(0):null);
            extData.put("goods", goodList);
            res.setExtData(extData);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }
	
	@SuppressWarnings("unchecked")
	public PageData updateApplyGoodsInfo(DataReq req) {
		Map<String, Object> param = req.getReqData();
		PageData res = new PageData();
		newg_status = begin_newg();// 开启事物
		param.put("tableName", "g_order_out_apply");
		try {
			param.put("keys", "uuid") ;
			PageData sqlInfo = getUpdateSQL(req);
			if (sqlInfo.getRetCode() != 0) {
				rollback_newg(newg_status);
				return sqlInfo;
			}
			final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
			final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
			this.getJdbcTemplate_newg().update(sb_field.toString(),
					listData.toArray());
			
			commit_newg(newg_status);
			res.setRetCode(0);
			res.setRetMessage("OK");
		} catch (Exception e) {
			rollback_newg(newg_status);
			e.printStackTrace();
			
		} finally {
			
		}
		return res;
	}
	
	@SuppressWarnings("unchecked")
	public PageData delApplyGoods(DataReq req) {rollback_newg(newg_status);
		Map<String, Object> param = req.getReqData();
		PageData res = new PageData();
		newg_status = begin_newg();// 开启事物
		param.put("tableName", "g_order_out_apply");
        param.put("isdelete","1");
		
		try {
			param.put("keys", "uuid");
			PageData sqlInfo = getUpdateSQL(req);
			if (sqlInfo.getRetCode() != 0) {
				rollback_newg(newg_status);
				return sqlInfo;
			}
			final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
			final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
			this.getJdbcTemplate_newg().update(sb_field.toString(),
					listData.toArray());
			
			commit_newg(newg_status);
			res.setRetCode(0);
			res.setRetMessage("OK");
			
		} catch (Exception e) {
			rollback_newg(newg_status);
			e.printStackTrace();
			
		} finally {
			
		}
		return res;
	}
	
	@SuppressWarnings("unchecked")
	public PageData delApply(DataReq req) {
		Map<String, Object> param = req.getReqData();
		PageData res = new PageData();
		newg_status = begin_newg();// 开启事物
		param.put("tableName", "g_order_out_apply");
        param.put("isdelete","1");
		
		try {
			param.put("keys", "applyId");
			PageData sqlInfo = getUpdateSQL(req);
			if (sqlInfo.getRetCode() != 0) {
				rollback_newg(newg_status);
				return sqlInfo;
			}
			final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
			final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
			this.getJdbcTemplate_newg().update(sb_field.toString(),
					listData.toArray());
			
			
			res.setRetCode(0);
			res.setRetMessage("OK");
			
			//删除关联申请单的出库单
			StringBuffer sb = new StringBuffer();
			sb.append("update g_order_out set isdelete='1' where applyId='").append(param.get("applyId")).append("' ");
			int i = this.getJdbcTemplate_newg().update(sb.toString());
			if(i<0) {
				res.setRetCode(9);
				res.setRetMessage("关联申请单的出库单删除失败!");
				rollback_newg(newg_status);
				return res;
			}
			commit_newg(newg_status);
		} catch (Exception e) {
			rollback_newg(newg_status);
			e.printStackTrace();
			
		} finally {
			
		}
		return res;
	}
	
	@SuppressWarnings("unchecked")
	public PageData submitOrderOutApply(DataReq req) {
		Map<String, Object> param = req.getReqData();
		PageData res = new PageData();
		newg_status = begin_newg();// 开启事物
		param.put("tableName", "g_order_out_apply");
        param.put("companyId", req.getUinfo().getCompanyId());
        param.put("orderState", "02");
		
		try {
			param.put("keys", "applyId");
			PageData sqlInfo = getUpdateSQL(req);
			if (sqlInfo.getRetCode() != 0) {
				rollback_newg(newg_status);
				return sqlInfo;
			}
			final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
			final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
			this.getJdbcTemplate_newg().update(sb_field.toString(),
					listData.toArray());
			
			commit_newg(newg_status);
			res.setRetCode(0);
			res.setRetMessage("OK");
		} catch (Exception e) {
			rollback_newg(newg_status);
			e.printStackTrace();
			
		} finally {
			
		}
		return res;
	}
	
	@SuppressWarnings("unchecked")
	public PageData submitOrderOutAudit(DataReq req) {
		Map<String, Object> param = req.getReqData();
		PageData res = new PageData();
		newg_status = begin_newg();// 开启事物
		param.put("tableName", "g_order_out_apply");
        param.put("companyId", req.getUinfo().getCompanyId());
        
        //审核结果
        if(!StringUtils.isEmpty((String) param.get("reviewerResult"))) {
        	if("01".equals(param.get("reviewerResult"))) {
        		param.put("orderState", "03");
        	}else if("02".equals(param.get("reviewerResult"))) {
        		param.put("orderState", "04");
        	}
        }
		
		try {
			param.put("keys", "applyId");
			PageData sqlInfo = getUpdateSQL(req);
			if (sqlInfo.getRetCode() != 0) {
				rollback_newg(newg_status);
				return sqlInfo;
			}
			final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
			final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
			this.getJdbcTemplate_newg().update(sb_field.toString(),
					listData.toArray());
			
			commit_newg(newg_status);
			res.setRetCode(0);
			res.setRetMessage("OK");
		} catch (Exception e) {
			rollback_newg(newg_status);
			e.printStackTrace();
			
		} finally {
			
		}
		return res;
	}
	
	//------------------------
	
	public PageData generateOrderId(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("生成出库单号失败");
        
        String orderId = null;
        try {
        	orderId = DBUtils.getDjbh(req.getUinfo().getCompanyId(), "CKD") ;
        	res.setKey(orderId);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }
	
	public PageData getOrderOutList(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("获取出库单登记列表失败");
        try {
            StringBuffer sb = new StringBuffer();
            StringBuffer sbfrom = new StringBuffer() ;
            sb.append("select a.orderId,a.orderType,b.`name` orderTypeName,a.warehouseKeeperID confirmID,c.nickName confirmName,a.warehouseTime,a.memo ,GROUP_CONCAT(DISTINCT d.goodsName) goodsNameList \n"
            		+ " from g_order_out a  \n"
            		+ " left join t_param b on a.orderType=b.`value` and b.param_type='98' \n"
            		+ " left join t_user c on a.warehouseKeeperID=c.id \n"
            		+ " left join (select a.orderId,b.goodsName from g_order_out a left join g_goods b on a.goodsUUid=b.uuid) d on a.orderId=d.orderId \n"
            		+ " where a.isdelete=0 and a.isReturn='0' and serial=1 and  a.companyId='").append(req.getUinfo().getCompanyId()).append("' ");
            
            //入库登记单ID
            if(!StringUtils.isEmpty((String) param.get("orderId"))) {
            	sb.append(" and a.orderId like '%").append(param.get("orderId")).append("%' ");
            }
            //申请类型
            if(!StringUtils.isEmpty((String) param.get("orderType"))) {
            	sb.append(" and a.orderType='").append(param.get("orderType")).append("' ");
            }
            //确认人
            if(!StringUtils.isEmpty((String) param.get("confirmName"))) {
            	sb.append(" and c.nickName like '%").append(param.get("confirmName")).append("%' ");
            }
            //登记开始时间
            if(!StringUtils.isEmpty((String) param.get("startTime"))) {
            	sb.append(" and a.warehouseTime >= '").append(param.get("startTime")).append("' ");
            }
            //登记结束时间
            if(!StringUtils.isEmpty((String) param.get("endTime"))) {
            	sb.append(" and a.warehouseTime < '").append(param.get("endTime")).append("' ");
            }
            
            sb.append("  GROUP BY a.orderId ");
            sb.append("  order by a.warehouseTime desc ");
            sb = DBUtils.sql_check(sb) ;
            sbfrom.append(sb.toString()) ;
            int idx=sbfrom.indexOf(" from ") ;
            sbfrom.delete(0, idx);
            sbfrom.insert(0," from ( select count(1) cnt ");
            sbfrom.append(") l");
            Page page = new Page(this.getJdbcTemplate_newg(),sbfrom.toString(),req.getPageid(),req.getPagesize(),res,new Object[]{}) ;
            sb.append(" limit ").append(page.getOffsetlimit()).append(",").append(req.getPagesize()) ;
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{});
            res.setPage(list);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }
	
	public PageData getApplyGoodsList(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("获取申请单商品列表失败");
        try {
            StringBuffer sb = new StringBuffer();
            StringBuffer sbfrom = new StringBuffer() ;
            sb.append("select a.uuid,a.applyId,a.goodsUUid,b.goodsCode,b.goodsName,a.orderType,b.goodsType,d.goodsTypeName,"
        			+ " b.goodsModel,b.packingSize,b.unit,a.customerId,if(c.companyName is not null and c.companyName!='',c.companyName,if(a.customerId is not null and a.customerId!='',a.customerId,'其他')) customerName,a.applyTime,a.inoutNum,a.memo,if(e.uuid is not null,sum(e.inoutNum),0) orderoutNum,"
            		+ " null currentNum,null warehouseId"
        			+ " from g_order_out_apply a\r\n"
        			+ " left join g_goods b on a.goodsUUid=b.uuid\r\n"
        			+ " left join t_company c on a.customerID=c.companyId\r\n"
        			+ " left join g_goodstype d on b.goodsType=d.goodsTypeId and d.companyId = b.companyId and d.deleted = 0\r\n"
        			+ " left join g_order_out e on a.goodsUUid=e.goodsUUid and a.applyId=e.applyId\r\n"
        			+ " where a.isdelete=0 and a.orderState='03' and a.companyId='").append(req.getUinfo().getCompanyId()).append("' ");
            
            //出库申请单ID
            if(!StringUtils.isEmpty((String) param.get("applyId"))) {
            	sb.append(" and a.applyId like '").append(param.get("applyId")).append("%' ");
            }
            //货品名称
            if(!StringUtils.isEmpty((String) param.get("goodsName"))) {
            	sb.append(" and b.goodsName	 like '").append(param.get("goodsName")).append("%' ");
            }
            //供货方名称
            if(!StringUtils.isEmpty((String) param.get("customerName"))) {
            	sb.append(" and c.companyName	 like '").append(param.get("customerName")).append("%' ");
            }
            //登记开始时间
            if(!StringUtils.isEmpty((String) param.get("startTime"))) {
            	sb.append(" and a.applyTime >= '").append(param.get("startTime")).append("' ");
            }
            //登记结束时间
            if(!StringUtils.isEmpty((String) param.get("endTime"))) {
            	sb.append(" and a.applyTime < '").append(param.get("endTime")).append("' ");
            }
        	sb.append(" group by a.applyId,a.goodsUUid having a.inoutNum > ifnull(sum(e.inoutNum),0) \r\n"
        			+ " order by a.applyTime desc ");
            
            
            sb = DBUtils.sql_check(sb) ;
            sbfrom.append(sb.toString()) ;
            int idx=sbfrom.indexOf(" from ") ;
            sbfrom.delete(0, idx);
            sbfrom.insert(0," from ( select count(1) cnt,a.inoutNum ");
            sbfrom.append(") l");
            Page page = new Page(this.getJdbcTemplate_newg(),sbfrom.toString(),req.getPageid(),req.getPagesize(),res,new Object[]{}) ;
            sb.append(" limit ").append(page.getOffsetlimit()).append(",").append(req.getPagesize()) ;
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{});
            res.setPage(list);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }
	
	//获取最新出库单ID的序号
	public Integer getOrderNewSerial(String orderId) {
		StringBuffer sb = new StringBuffer();
		sb.append("select serial from g_order_out where orderId='"+orderId+"' order by serial desc limit 1 ");
		List<Map<String, Object>> serial = this.getJdbcTemplate_newg().queryForList(sb.toString());
		if(serial.size()>0) {
			return (Integer) serial.get(0).get("serial");
		}else {
			return null;
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public PageData submitOrderOutConfirm(DataReq req) {
		Map<String, Object> param = req.getReqData();
		PageData res = new PageData();
		newg_status = begin_newg();// 开启事物
		param.put("tableName", "g_order_out");
        param.put("isdelete","0");
        param.put("isReturn","0");
        param.put("companyId", req.getUinfo().getCompanyId());
		JSONArray goodslist = (JSONArray) param.get("goodslist");
		try {
			
	        for(int i=0;i<goodslist.size();i++) {
	        	JSONObject object = (JSONObject)goodslist.get(i);
	        	param.put("applyId", object.get("applyId"));
	        	param.put("orderType", object.get("orderType"));
	        	param.put("goodsUUid", object.get("goodsUUid"));
	        	JSONArray dtos = (JSONArray) object.get("list");
	        	for(int j=0;j<dtos.size();j++) {
	        		param.remove("uuid");
	        		JSONObject dto = (JSONObject) dtos.get(j);
	        		param.put("goodsUUid", object.get("goodsUUid"));
	        		param.put("inoutNum", String.valueOf(dto.get("inoutNum")));
	        		param.put("warehouseId", dto.get("warehouseId"));
	        		
	        		//出库数量为0 继续
	        		if("0".equals(String.valueOf(dto.get("inoutNum")))) {
	        			continue;
	        		}
	        		//判断要出库的数量是否大于(申请数量-已出库的数量)
		        	boolean result = isOutOrderOutCount(Integer.parseInt(String.valueOf(dto.get("inoutNum"))),String.valueOf(object.get("applyId"))
		        			,String.valueOf(param.get("orderId")),String.valueOf(object.get("goodsUUid")));
		        	if(result) {
		        		rollback_newg(newg_status);
		        		res.setRetCode(9);
		    			res.setRetMessage("货品数量超出未出库数量!");
		        	}
		        	//设置序号
			        Integer serial = getOrderNewSerial((String) param.get("orderId"));
			        if(serial!=null) {
			        	param.put("serial", String.valueOf(serial+1));
			        }else {
			        	param.put("serial", "1");
			        }
					PageData sqlInfo = getInsertSQL(req);
					if (sqlInfo.getRetCode() != 0) {
						rollback_newg(newg_status);
						return sqlInfo;
					}
					final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
					final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
					this.getJdbcTemplate_newg().update(sb_field.toString(),
							listData.toArray());
	        	}
	        	//修改申请单状态为出库成功
		        orderOutSuccess(String.valueOf(object.get("applyId")));
	        }
	        
	        //保存到库存
			String orderId = (String) param.get("orderId");
			String orderType = (String) param.get("orderType");
			res = inventoryDaoImpl.changeInventory(orderType, orderId,"0");
			if(res.getRetCode()!=0) {
				rollback_newg(newg_status);
			}else {
				commit_newg(newg_status);
			}
			
			//判断是否有purchaseId
			StringBuffer sb = new StringBuffer();
			sb.append("select a.purchaseId from g_order_out_apply a where a.applyId='").append(param.get("applyId")).append("' limit 1 ");
			List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString());
			String purchaseId = (String) list.get(0).get("purchaseId");
			if(!StringUtils.isEmpty(purchaseId)) {
				//生成代理商入库申请单
				generateOrderInApply(req,String.valueOf(param.get("orderId")));
			}
			
		} catch (Exception e) {
			rollback_newg(newg_status);
			e.printStackTrace();
			
		} finally {
			
		}
		return res;
	}
	
	public boolean isOutOrderOutCount(Integer inNum,String applyId,String orderId,String goodsUUid) {
		boolean result = false;
		StringBuffer sb = new StringBuffer();
		try {
			//根据applyId和goodsUUid获取商品申请数量
			sb.delete(0, sb.length());
			sb.append("select inoutNum from g_order_out_apply a where a.applyId='").append(applyId).append("'")
			.append(" and a.goodsUUid='").append(goodsUUid).append("' ");
			int inoutNum = this.getJdbcTemplate_newg().queryForObject(sb.toString(), Integer.class);
			//获取已出库的数量
			sb.delete(0, sb.length());
			sb.append("select IFNULL(sum(a.inoutNum),0) cnt from g_order_out a where a.orderId='").append(orderId).append("'")
			.append(" and a.applyId='").append(applyId).append("'")
			.append(" and a.goodsUUid='").append(goodsUUid).append("' ");
			int cnt = this.getJdbcTemplate_newg().queryForObject(sb.toString(), Integer.class);
			int f = inoutNum-cnt;
			if(inNum>f) {
				result = true;
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			
		}
		return result;
	}
	
	public boolean orderOutSuccess(String applyId) {
		boolean result = false;
		StringBuffer sb = new StringBuffer();
		try {
			//根据applyId获取申请单商品数量和入库单商品数量
			sb.delete(0, sb.length());
			sb.append("select if(sum(l.applyCount)=sum(l.orderoutCount),1,0) flag\r\n"
					+ "	from(\r\n"
					+ "	select sum(a.inoutNum) applyCount,0 orderoutCount\r\n"
					+ "	from g_order_out_apply a \r\n"
					+ "	where a.isdelete=0 and a.applyId=?\r\n"
					+ "	union\r\n"
					+ "	select 0 applyCount,sum(a.inoutNum) orderoutCount\r\n"
					+ "	from g_order_out a \r\n"
					+ "	where a.isdelete=0 and a.applyId=?\r\n"
					+ "	) l");
			int flag = this.getJdbcTemplate_newg().queryForObject(sb.toString(),new Object[] {applyId,applyId}, Integer.class);
			if(flag>0) {
				sb.delete(0, sb.length());
				sb.append("update g_order_out_apply set orderState='05' where applyId='").append(applyId).append("' ");
				int i = this.getJdbcTemplate_newg().update(sb.toString());
				if(i>0) {
					result = true;
				}
			}
			
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			
		}
		return result;
	}
	
	//生成代理商入库申请单
	public void generateOrderInApply(DataReq req,String orderId){
		newg_status = begin_newg();// 开启事物
		StringBuffer sb = new StringBuffer();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		//获取出库单数据列表
		try {
			sb.delete(0, sb.length());
			sb.append("select b.purchaseId,a.serial,b.companyId,b.departmentId,b.applyUid,b.applyTime,"
					+ "b.customerId,b.customerName,b.address,b.phone,b.cusname,b.goodsUUid,sum(a.inoutNum) inoutNum,"
					+ "a.memo,b.reviewerId,b.reviewerTime\r\n"
					+ "from g_order_out a\r\n"
					+ "left join (\r\n"
					+ "	select a.purchaseId,b.applyId,a.companyId,a.departmentId,a.applyUid,a.applyTime,a.customerID,a.customerName,a.address,a.phone,a.cusname,a.goodsUUid,a.companyGoodsId,a.memo,a.reviewerId,a.reviewerTime\r\n"
					+ "	from g_purchase a\r\n"
					+ "	left join g_order_out_apply b on a.purchaseId=b.purchaseId and b.serial=1\r\n"
					+ "	where a.isdelete=0 \r\n"
					+ ") b on a.applyId=b.applyId and a.goodsUUid=b.companyGoodsId\r\n"
					+ "\r\n"
					+ "where a.isdelete=0 and a.orderId=?");
			sb.append("group by b.goodsUUid ");
			List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(),new Object[] {orderId});
			
			
			//生成申请单
			DataReq req1 = new DataReq();
			req1.setUinfo(req.getUinfo());
			PageData res = generateApplyId(req1);
			String applyId = res.getKey();
			//插入到入库申请表
			for(int i=0;i<list.size();i++) {
				//生成uuid
				UUID uuid = UUID.randomUUID();
				//设置序号
				Integer orderNewSerial = orderInDaoImpl.getApplyNewSerial(applyId);
		        String serial = orderNewSerial!=null?String.valueOf(orderNewSerial):null;
		        if(serial!=null) {
		        	serial = String.valueOf(Integer.parseInt(serial)+1);
		        }else {
		        	serial = "1";
		        }
				String purchaseId = (String) list.get(i).get("purchaseId");
//				Integer serial = (Integer) list.get(i).get("serial");
				String companyId = (String) list.get(i).get("companyId");
				String departmentId = (String) list.get(i).get("departmentId");
				Long applyUid = (Long) list.get(i).get("applyUid");
				String customerId = (String) list.get(i).get("customerId");
				String customerName = (String) list.get(i).get("customerName");
				String address = (String) list.get(i).get("address");
				String phone = (String) list.get(i).get("phone");
				String cusname = (String) list.get(i).get("cusname");
				String goodsUUid = (String) list.get(i).get("goodsUUid");
				BigDecimal inoutNum = (BigDecimal) list.get(i).get("inoutNum");
				String memo = (String) list.get(i).get("memo");
				Long reviewerId = (Long) list.get(i).get("reviewerId");
				String orderType = "01";
				String orderState = "03";
				String reviewerResult = "01";
				String reviewerSuggest = "通过";
				String applyTime = sdf.format(new Date());
				String reviewerTime = sdf.format(new Date());
				String isdelete = "0";
				sb.delete(0, sb.length());
				sb.append("insert into g_order_in_apply(uuid,applyId,purchaseId,serial,orderType,"
						+" orderState,companyId,departmentId,applyUid,applyTime,customerID,customerName,"
						+ "address,phone,cusname,goodsUUid,inoutNum,memo,reviewerId,reviewerTime,"
						+ "reviewerResult,reviewerSuggest,isdelete) ");
				sb.append("values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
				this.getJdbcTemplate_newg().update(sb.toString(),new Object[] {uuid.toString(),applyId,purchaseId,serial,
						orderType,orderState,companyId,departmentId,applyUid,applyTime,customerId,customerName,
						address,phone,cusname,goodsUUid,inoutNum,memo,reviewerId,reviewerTime,reviewerResult,
						reviewerSuggest,isdelete});
			}
			commit_newg(newg_status);
		}catch(Exception e) {
			rollback_newg(newg_status);
			e.printStackTrace();
		}finally {
			
		}
	}
	
	public PageData getOrderOutDetail(DataReq req) {
        Map<String, Object> param = req.getReqData();
        Map<String,Object> extData = new HashMap();
        PageData res = new PageData();
        StringBuffer sb = new StringBuffer();
        res.setRetCode(9);
        res.setRetMessage("获取出库登记详情失败");
        try {
            sb.append("select a.orderId,a.warehouseKeeperID,a.warehouseTime,a.memo\r\n"
            		+ "from g_order_out a\r\n"
            		+ "where a.isdelete=0 and a.orderId=?\r\n"
            		+ "limit 1");
            
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{param.get("orderId")});
            extData = list.get(0);
            //获取商品列表
            if(list!=null && list.size()>0) {
            	sb.delete(0, sb.length());
            	sb.append("select a.applyId,a.goodsUUid,b.goodsCode,b.goodsName,a.orderType,b.goodsType,d.goodsTypeName,b.goodsModel,b.packingSize,b.unit,c.customerId,e.companyName customerName,c.applyTime,c.inoutNum,c.memo,sum(f.inoutNum) orderoutNum,a.inoutNum currentNum,a.warehouseId,true flagshow\r\n"
            			+ "from g_order_out a\r\n"
            			+ "left join g_goods b on a.goodsUUid=b.uuid\r\n"
            			+ "left join g_order_out_apply c on a.applyId=c.applyId and a.goodsUUid=c.goodsUUid\r\n"
            			+ "left join g_goodstype d on b.goodsType=d.goodsTypeId and d.companyId = b.companyId and d.deleted = 0 \r\n"
            			+ "left join t_company e on c.customerID=e.companyId\r\n"
            			+ "left join g_order_out f on a.goodsUUid=f.goodsUUid and a.applyId=f.applyId\r\n"
            			+ "where a.isdelete=0 and a.orderId=?\r\n"
            			+ "group by a.applyId,a.goodsUUid\r\n"
            			+ "order by a.serial asc,a.warehouseTime asc");
            	List<Map<String, Object>> goodslist = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{param.get("orderId")});
            	extData.put("goodslist", goodslist);
            	
            	//根据商品ID获取入库信息
            	for(int i=0;i<goodslist.size();i++) {
            		String goodsUUid = (String) goodslist.get(i).get("goodsUUid");
            		String applyId = (String) goodslist.get(i).get("applyId");
            		sb.delete(0, sb.length());
            		sb.append("select a.goodsUUid goodsid,a.inoutNum,a.warehouseId\r\n"
            				+ "from g_order_out a\r\n"
            				+ "where a.isdelete=0 and a.orderId=? and a.goodsUUid='").append(goodsUUid).append("' and a.applyId='").append(applyId).append("' ");
            		List<Map<String, Object>> infolist = this.getJdbcTemplate_newg().queryForList(sb.toString(),new Object[] {param.get("orderId")});
            		goodslist.get(i).put("list", infolist);
            	}
            }
           
            res.setExtData(extData);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }
	
	public PageData orderOutReturn(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        newg_status = begin_newg();// 开启事物
        param.put("tableName", "g_order_out");
        StringBuffer sb = new StringBuffer();
        res.setRetCode(9);
        res.setRetMessage("出库单冲账失败");
        try {
            
        	//根据订单获取要冲账的货品
        	sb.append("select a.uuid,a.applyId,a.orderType,a.companyId,a.goodsUUid,a.inoutNum,a.memo,a.warehouseId,a.warehouseName,a.warehouseKeeperID,a.warehouseTime\r\n"
        			+ "from g_order_out a\r\n"
        			+ "where a.isdelete=0 and a.orderId='").append(param.get("orderId")).append("' ");
        	List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(),new Object[] {});
        	Set<String> applyIds = new HashSet<String>();
        	for(int i=0;i<list.size();i++) {
        		Map<String,Object> li = list.get(i);
        		applyIds.add((String) li.get("applyId"));
        		
        		param.put("applyId", li.get("applyId"));
        		param.put("orderType", li.get("orderType"));
        		param.put("companyId", li.get("companyId"));
        		param.put("goodsUUid", li.get("goodsUUid"));
        		BigDecimal inoutNum = (BigDecimal) li.get("inoutNum");
        		param.put("inoutNum", inoutNum.negate().setScale(0,BigDecimal.ROUND_DOWN).longValue());
        		param.put("memo", li.get("memo"));
        		param.put("warehouseId", li.get("warehouseId"));
        		param.put("warehouseName", li.get("warehouseName"));
        		param.put("warehouseKeeperID", li.get("warehouseKeeperID"));
        		param.put("warehouseTime", li.get("warehouseTime"));
        		param.put("returnUuid", li.get("uuid"));
        		param.put("isReturn", "1");
        		param.put("isdelete", "0");
        		param.put("uuid", UUID.randomUUID().toString());
        		//设置序号
		        Integer serial = getOrderNewSerial((String) param.get("orderId"));
		        if(serial!=null) {
		        	param.put("serial", String.valueOf(serial+1));
		        }else {
		        	param.put("serial", "1");
		        }
        		PageData sqlInfo = getInsertSQL(req);
    			if (sqlInfo.getRetCode() != 0) {
    				rollback_newg(newg_status);
    				return sqlInfo;
    			}
    			final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
    			final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
    			this.getJdbcTemplate_newg().update(sb_field.toString(),
    					listData.toArray());
        	}
        	commit_newg(newg_status);
            res.setRetCode(0);
            res.setRetMessage("OK");
            
          //保存到库存
			String orderId = (String) param.get("orderId");
			String orderType = (String) list.get(0).get("orderType");
			res = inventoryDaoImpl.changeInventory(orderType, orderId,"1");
			
			//更新orderId为冲账
            sb.delete(0, sb.length());
            sb.append("update g_order_out set isReturn='1' where orderId='").append(param.get("orderId")).append("' ");
            this.getJdbcTemplate_newg().update(sb.toString());
            
         // list获取申请单ID 修改申请单状态为03
            Iterator<String> iterator = applyIds.iterator();
            while(iterator.hasNext()) {
            	String next = iterator.next();
            	sb.delete(0, sb.length());
    			sb.append("update g_order_out_apply set orderState='03' where applyId='").append(next).append("' ");
    			this.getJdbcTemplate_newg().update(sb.toString());
            }
        } catch (Exception e) {
        	rollback_newg(newg_status);
            e.printStackTrace();
        } finally {

        }
        return res;
    }
}
